import React, { FC } from "react";
import { message, Upload } from "antd";
import type { UploadProps } from "antd";
import ImgCrop from "antd-img-crop";
import { getItem } from "@/utils/localstorage";
import styles from "./index.less";
interface propType {
  aspect?: number;
  cropShape?: "rect" | "round";
  fileSize?: number;
  btnText?: string;
  accept?: string;
  onSuccess: (url: any) => void;
}
const UploadPreview: FC<propType> = (props) => {
  const {
    aspect = 1,
    cropShape = "rect",
    onSuccess,
    fileSize = 5,
    btnText,
    accept = ".png,.jpg,.jpeg",
  } = props;
  const onChange: UploadProps["onChange"] = ({ fileList: newFileList }) => {
    if (newFileList.length > 0) {
      let info = newFileList[0];
      if (info.status === "uploading") {
      } else if (info.status === "done") {
        console.log(info.response.data);
        onSuccess && onSuccess(info.response.data);
      } else if (info.status === "error") {
        message.error(`${info.name}文件上传失败`);
      }
    } else {
      onSuccess && onSuccess("");
    }
  };
  const beforeUpload = (file) => {
    const isLt2M = file.size / 1024 / 1024 < fileSize;
    if (!isLt2M) {
      message.error(`图片大小不能大于${fileSize}MB!`);
    }
    return isLt2M;
  };
  return (
    <div className={styles.UploadPreviewBox}>
      <ImgCrop aspect={aspect} cropShape={cropShape}>
        <Upload
          maxCount={1}
          name="file"
          accept={accept}
          headers={{
            clientid: "e5cd7e4891bf95d1d19206ce24a7b32e",
            Authorization: getItem("token"),
          }}
          beforeUpload={beforeUpload}
          action="/spark-frontend/system/user/uploadPic"
          listType="picture-card"
          onChange={onChange}
          style={{ width: "200px", height: "200px" }}
        >
          {btnText ? btnText : "+ 上传文件"}
        </Upload>
      </ImgCrop>
    </div>
  );
};

export default UploadPreview;
